const fs = require('fs').promises;
const path = require('path');
const { marked } = require('marked');

// 配置marked选项
marked.setOptions({
  headerIds: true,
  gfm: true,
  breaks: true,
  sanitize: false
});

// 处理HTML内容，移除多余的空行和回车
function cleanHtml(html) {
  return html
    .split('\n')
    .map(line => line.trim())
    .filter(line => line.length > 0)
    .join('\n');
}

// 转换单个文件
async function convertFile(filePath, outputDir) {
  try {
    // 读取markdown文件
    const content = await fs.readFile(filePath, 'utf-8');
    
    // 转换为HTML
    const html = marked(content);
    
    // 清理HTML
    const cleanedHtml = cleanHtml(html);
    
    // 创建输出文件路径
    const fileName = path.basename(filePath, '.md') + '.html';
    const outputPath = path.join(outputDir, fileName);
    
    // 写入文件
    await fs.writeFile(outputPath, cleanedHtml, 'utf-8');
    console.log(`Successfully converted ${fileName}`);
  } catch (error) {
    console.error(`Error converting ${filePath}:`, error);
  }
}

// 主函数
async function processMarkdownFiles() {
  try {
    // 创建输出目录
    const outputDir = path.join(__dirname, 'standard-html-files');
    await fs.mkdir(outputDir, { recursive: true });
    
    // 读取files目录
    const filesDir = path.join(__dirname, 'files');
    const files = await fs.readdir(filesDir);
    
    // 过滤出markdown文件并处理
    const mdFiles = files.filter(file => file.endsWith('.md'));
    
    for (const file of mdFiles) {
      await convertFile(path.join(filesDir, file), outputDir);
    }
    
    console.log('All files processed successfully');
  } catch (error) {
    console.error('Error processing files:', error);
  }
}

// 执行转换
processMarkdownFiles();